﻿using BF;
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;

/// <summary>
/// 用户数据：使用BF/PlayerData/Creat PlayerData.cs自动生成
/// </summary>
public static class PlayerData
{

    private static readonly PlayerDataInfo[] allInfos = new PlayerDataInfo[] {
    };

    static PlayerData()
    {
        if (!Application.isPlaying)
        {
            return;
        }

        Timer.Pop().Delay(5).Loop(-1, 60).Action(AutoSave).Execute();

        UnityMonoEvent.onApplicationPause += (isPause) => SaveAll();
        UnityMonoEvent.onApplicationFocus += (isFocus) => SaveAll();
        UnityMonoEvent.onApplicationQuit += () => SaveAll();
    }

    public static void Clear<T>() where T : PlayerDataInfo, new()
    {
        string propertyName = typeof(T).Name;
        propertyName = char.ToLower(propertyName[0]) + propertyName.Substring(1);
        FieldInfo field = typeof(PlayerData).GetField(propertyName);
        T newInfo = PlayerDataInfo.New<T>();
        field?.SetValue(null, newInfo);
        for (int i = 0; i < allInfos.Length; ++i)
        {
            if (allInfos[i].GetType().Equals(typeof(T)))
            {
                allInfos[i] = newInfo;
                break;
            }
        }
    }

    private static void AutoSave()
    {
        foreach(PlayerDataInfo info in allInfos)
        {
            if (info.isAutoSave)
            {
                info.Save();
            }
        }
        PlayerPrefs.Save();
    }

    public static void SaveAll()
    {
        foreach (PlayerDataInfo info in allInfos)
        {
            info.Save();
        }
        PlayerPrefs.Save();
    }
}

